package Data;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class Cmdsh {

	static String hostname = null;;
	static String username = null;
	static String identity = null;
	static String password = null;
	
	public static void main(String[] args) {
		String[] command = { "mkdir /Ara/aaa" };
		List<String> ret = exec(command);
		
		for(int i=0; i<ret.size(); i++){
		System.out.println(ret.get(i)+"\n");
		}
	}

	private static Session getSession() throws JSchException {

		username = "root";
		hostname = "192.168.238.128";
		password = "hadoop";

		JSch jsch = new JSch();
		if (identity != null) {
			jsch.addIdentity(identity);
		}
		Session session = jsch.getSession(username, hostname, 22);
		session.setConfig("StrictHostKeyChecking", "no");
		if (password != null) {
			session.setPassword(password);
		}
		return session;
	}

	public static List<String> exec(String[] commands) {
		List<String> ret = new ArrayList<String>();
		try {
			Session session = getSession();
			session.connect();
			for (String command : commands) {
				ChannelExec channelExec = (ChannelExec) session
						.openChannel("exec");
				channelExec.setPty(true);
				channelExec.setCommand(command);
				InputStream inputStream = channelExec.getInputStream();
				channelExec.connect(3000);

				String output = "";
				byte[] buf = new byte[1024];
				int length;
				while ((length = inputStream.read(buf)) != -1) {
					output += new String(buf, 0, length);
				}
				ret.add(StringUtils.chop(output));
				channelExec.disconnect();
			}
			session.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	
}
